from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.hashers import make_password
from .. import models
from django.core.urlresolvers import reverse
from myweb.settings import BASE_DIR
from .views_index import uploads
import os

# Create your views here.

# 后台用户 列表
def userindex(request):
    # 获取所有的用户数据
    data = models.users.objects.filter().exclude(status=2)

    #获取搜索条件和参数
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')
    #判断是否有搜索条件
    if types:
        #多字段搜索
        if types=='all':
            # 引入Q对象
            from django.db.models import Q
            data = data.filter(Q(name__contains=keywords)|Q(phone__contains=keywords)|Q(email__contains=keywords)|Q(age__contains=keywords)|Q(sex__contains=keywords))
        elif types =='status':
            dict1={'正常':0,'禁用':1,'删除':2}
            data = data.filter(status=dict1[keywords])
        #单个字段查询
        else:
            search = {types+'__contains':keywords}
            data = data.filter(**search)

    #数据分页
    from django.core.paginator import Paginator

    # 实例化分页类 参数1,获取的所有的数据对象   参数2 每页显示多少条
    paginator = Paginator(data, 20)

    # 获取当前页码数  ?p=n
    p = request.GET.get('p', 1)

    # 获取当前页的数据
    userlist = paginator.page(p)


    # 分配数据
    context = {'userlist': userlist}

    return render(request, 'myadmin/users/index.html', context)
    # 加载模板

#会员管理 显示
def useradd(request):
    # 判断当前的请求方式
    if request.method == 'GET':
        # 加载表单页面
        return render(request, 'myadmin/users/add.html')
    elif request.method == 'POST':
        try:
            # 接收数据,进行数据
            data = request.POST.dict()
            data.pop("csrfmiddlewaretoken")
            # 密码加密
            # 对密码进行加密操作
            data['password'] = make_password(data['password'], None, 'pbkdf2_sha256')
            # 头像上传
            myfile = request.FILES.get('Headpic')
            if myfile:
                # 调用函数进行头像上传
                data['Headpic'] = uploads(myfile)
            else:
                data['Headpic'] = '/static/myadmin/img/3.jpg'
            # 进行数据的添加
            ob = models.users(**data)
            ob.save()
            return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_user_index')+'"</script>')
        except:
            return HttpResponse('<script>alert("添加失败");location.href="' + reverse('myadmin_user_add') + '"</script>')

# 会员删除  逻辑删除
def userdel(request, uid):
    try:
        # 根据uid获取用户对象,修改状态
        ob = models.users.objects.get(id=uid)
        ob.status = 2
        ob.save()

        return HttpResponse(
            '<script>alert("删除成功");location.href="' + reverse('myadmin_user_index') + '"</script>')
    except:
        return HttpResponse(
            '<script>alert("删除失败");location.href="' + reverse('myadmin_user_index') + '"</script>')


# 显示编辑表单,执行编辑
def useredit(request, uid):
    # 根据uid获取用户对象
    ob = models.users.objects.get(id=uid)
    # 判断请求方式
    if request.method == 'GET':
        # 显示编辑表单
        return render(request, 'myadmin/users/edit.html', {'uinfo': ob})

    elif request.method == 'POST':
        # 执行编辑
        ob.name = request.POST.get('name')
        # 密码判断
        if request.POST.get('password'):
            # 修改
            ob.password = make_password(request.POST['password'], None, 'pbkdf2_sha256')
        ob.phone = request.POST.get('phone')
        ob.email = request.POST.get('email')
        ob.age = request.POST.get('age')
        ob.sex = request.POST.get('sex')
        # 判断是否更新了头像
        myfile = request.FILES.get('Headpic')
        if myfile:
            # 如果修改了头像,要上传新的头像,并判断是否删除以前头像
            if ob.Headpic != '/static/myadmin/img/3.jpg':
                # 删除原来上传的头像
                os.remove(BASE_DIR + ob.Headpic)

            # 更新头像
            ob.Headpic = uploads(myfile)
        # 执行数据的更新
        ob.save()

        return HttpResponse(
            '<script>alert("更新成功");location.href="' + reverse('myadmin_user_index') + '"</script>')

